#include "mysql.h"





int get_file_hash_from_db(const char *now_addr,MYSQL*mysql,char*md5) {
    char query[256];
    snprintf(query, sizeof(query), 
             "SELECT md5 FROM vft WHERE path='%s'",now_addr);

   mysql_query(mysql, query);
   MYSQL_RES *rows=mysql_store_result(mysql);
   if(mysql_num_rows(rows)==0){
       return -1;
   }
    MYSQL_ROW row=mysql_fetch_row(rows);
    md5=row[0];

   // MYSQL_RES *result = mysql_store_result(db_conn);
   // if (!result) {
   //   fprintf(stderr, "Store result error: %s\n", mysql_error(db_conn));
   // return -1;
   // }

    //MYSQL_ROW row = mysql_fetch_row(result);
    //if (!row) {
    //   fprintf(stderr, "File not found: %s\n", filename);
    //    mysql_free_result(result);
    //    return -1;
    //}

    // 复制哈希值到输出参数

    //mysql_free_result(result);
    return 1;
}


int db_check_hash(const char *hash) {
    char query[256];
    snprintf(query, sizeof(query), "SELECT  FROM vft WHERE md5='%s'", hash);

    if (mysql_query(db_conn, query)) {
        fprintf(stderr, "Query error: %s\n", mysql_error(db_conn));
        return -1;
    }

    MYSQL_RES *result = mysql_store_result(db_conn);
    bool exists = (mysql_num_rows(result) > 0);
    mysql_free_result(result);

    return 1;
}

int db_insert_file(const char *name, const char *path, size_t size, const char *hash) {
    char query[512];
    snprintf(query, sizeof(query),
        "INSERT INTO files (file_name, file_path, file_size, file_hash) "
        "VALUES ('%s', '%s', %zu, '%s')",
        name, path, size, hash);

    if (mysql_query(db_conn, query)) {
        fprintf(stderr, "Insert error: %s\n", mysql_error(db_conn));
        return -1;
    }

    printf("File record inserted: %s\n", name);
    return 1;
}

void db_close() {
    if (db_conn) {
        mysql_close(db_conn);
        printf("MySQL connection closed.\n");
    }
}
